package cn.csc.module.order.controller.admin.item;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.excel.core.util.ExcelUtils;
import cn.csc.framework.operatelog.core.annotations.OperateLog;
import cn.csc.module.member.api.user.MemberUserApi;
import cn.csc.module.member.api.user.dto.MemberUserRespDTO;
import cn.csc.module.order.api.order.dto.OrderStatusRespDTO;
import cn.csc.module.order.controller.admin.item.vo.*;
import cn.csc.module.order.controller.admin.order.vo.OrderWithItemRespVO;
import cn.csc.module.order.controller.app.vo.OrderItemReqVO;
import cn.csc.module.order.convert.item.OrderItemConvert;
import cn.csc.module.order.dal.dataobject.item.OrderItemDO;
import cn.csc.module.order.dal.dataobject.order.OrderDO;
import cn.csc.module.order.service.item.OrderItemService;
import cn.csc.module.order.service.order.OrderService;
import cn.csc.module.shop.api.user.ShopUserApi;
import cn.csc.module.shop.api.user.dto.ShopUserRespDTO;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.csc.framework.common.pojo.CommonResult.success;
import static cn.csc.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.csc.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Api(tags = "管理后台 - 订单项")
@RestController
@RequestMapping("/order/item")
@Validated
@Slf4j
public class OrderItemController {

    @Resource
    private OrderItemService itemService;
    @Resource
    private MemberUserApi memberUserApi;
    @Resource
    private ShopUserApi shopUserApi;
    @Resource
    private OrderService orderService;
    @PostMapping("/create")
    @ApiOperation("创建订单项")
    @PreAuthorize("@ss.hasPermission('order:item:create')")
    public CommonResult<BigInteger> createItem(@Valid @RequestBody OrderItemCreateReqVO createReqVO) {
        return success(itemService.createItem(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新订单项")
    @PreAuthorize("@ss.hasPermission('order:item:update')")
    public CommonResult<Boolean> updateItem(@Valid @RequestBody OrderItemUpdateReqVO updateReqVO) {
        itemService.updateItem(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除订单项")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = BigInteger.class)
    @PreAuthorize("@ss.hasPermission('order:item:delete')")
    public CommonResult<Boolean> deleteItem(@RequestParam("id") BigInteger id) {
        itemService.deleteItem(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得订单项")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = BigInteger.class)
    @PreAuthorize("@ss.hasPermission('order:item:query')")
    public CommonResult<OrderItemRespVO> getItem(@RequestParam("id") BigInteger id) {
        OrderItemDO item = itemService.getItem(id);
        return success(OrderItemConvert.INSTANCE.convert(item));
    }

    @GetMapping("/list")
    @ApiOperation("获得订单项列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('order:item:query')")
    public CommonResult<List<OrderItemRespVO>> getItemList(@RequestParam("ids") Collection<BigInteger> ids) {
        List<OrderItemDO> list = itemService.getItemList(ids);
        return success(OrderItemConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得订单项分页")
    @PreAuthorize("@ss.hasPermission('order:item:query')")
    public CommonResult<PageResult<OrderWithItemPageRespVO>> getItemmPage(@Valid OrderWithItemPageReqVO pageVO) {
        log.info("[OrderItemController][getItemPage][pageVO]=={}",pageVO);
        //取当前登录人是否是供应商，是提取出shopId
        MemberUserRespDTO memberUserRespDTO= memberUserApi.getUser(getLoginUserId()).getCheckedData();
        log.info("[OrderItemController][getItemPage][memberUserRespDTO]=={}",memberUserRespDTO);
        CommonResult<ShopUserRespDTO> shopUser = shopUserApi.getShopUser();// 查供应商数据
        if (shopUser.getCode() == 0) {
            ShopUserRespDTO shopUserRespDTO = shopUser.getData();
            if (shopUserRespDTO != null && shopUserRespDTO.getShopId() != null)
                pageVO.setShopId(shopUser.getData().getShopId());
        }
//        if(!Objects.isNull(memberUserRespDTO) &&  memberUserRespDTO.getType()==10 ){
//            ShopUserRespDTO shopUserRespDTO=shopUserApi.getShopUser().getCheckedData();
//            Optional.ofNullable(shopUserRespDTO).ifPresent(s -> pageVO.setShopId(shopUserRespDTO.getShopId()));
//        }
        PageResult<OrderWithItemPageRespVO> pageResult = itemService.selectOrderItemsPage(pageVO);
        List<OrderWithItemPageRespVO> list= pageResult.getList();
        if(!CollectionUtils.isEmpty(list)){
            List<BigInteger> orderIds=list.stream().map(e ->e.getOrderId()).collect(Collectors.toList());
            List<OrderDO> order=orderService.getList(orderIds);
            List<OrderItemDO> itemLists=itemService.getItemListByOrderId(orderIds,pageVO.getOrderStatus()==null?4:pageVO.getOrderStatus(),pageVO.getShopId());
            List<OrderWithItemPageRespVO> resultList= new ArrayList<>();
            for(OrderWithItemPageRespVO vo:list){//组装数据
                OrderItemReqVO reqVO = new OrderItemReqVO();
                reqVO.setOrderId(vo.getOrderId());
                List<OrderItemDO> itemList=itemLists.stream().filter(e->e.getOrderId().equals(vo.getOrderId())).collect(Collectors.toList());//itemService.getItemList(reqVO);

                OrderWithItemPageRespVO resultVo= OrderItemConvert.INSTANCE.convert03(!CollectionUtils.isEmpty(itemList)?itemList.get(0):new OrderItemDO());
                OrderDO orderDO=order.stream().filter(e -> e.getId().equals(vo.getOrderId())).findFirst().orElse(null) ;
                resultVo.setId(vo.getId());
                resultVo.setOutTradeNo(orderDO.getOutTradeNo());
                resultVo.setNickName(orderDO.getNickName());

                List<BigInteger> shopIds=itemList.stream().map(OrderItemDO:: getShopId ).distinct().collect(Collectors.toList());
                List<OrderItemListRespVO>  orderWithItemRespVOs= new ArrayList<>();
                for(BigInteger shopId : shopIds){
                    OrderItemReqVO reqVO1 = new OrderItemReqVO();
                    reqVO1.setOrderId(vo.getOrderId());
                    reqVO1.setShopId(shopId);
                    List<OrderItemDO> resultItemList=itemService.getItemList(reqVO1);
                    OrderItemListRespVO resultVOs=  new OrderItemListRespVO();
                    resultVOs.setOrderId(vo.getOrderId())
                             .setShopId(shopId)
                             .setShopName(resultItemList.get(0).getShopName())
                             .setOrderStatus(resultItemList.get(0).getOrderStatus())
                             .setPayTime(resultItemList.get(0).getPayTime())
                             .setOrderItems(OrderItemConvert.INSTANCE.convertList(resultItemList))
                             .setAllCount(resultItemList.stream().map(e -> e.getCount()).reduce(Integer::sum).get()) //订单产品数量
                             .setTotal(resultItemList.stream().map(OrderItemDO::getSpuTotalAmount).reduce(BigDecimal.ZERO,BigDecimal::add)) //订单的总金额
                             .setCardPayAmount(resultItemList.stream()
                                     .map(OrderItemDO::getCardPayAmount)
                                     .filter(Objects::nonNull)
                                     .reduce(BigDecimal.ZERO, BigDecimal::add));
                    orderWithItemRespVOs.add(resultVOs);
                }
                resultVo.setOrderWithItemRespVOs(orderWithItemRespVOs);
                resultList.add(resultVo);
            }
            pageResult.setList(resultList);
        }
        return success(pageResult);

    }

    @GetMapping("/export-excel")
    @ApiOperation("导出订单项 Excel")
    @PreAuthorize("@ss.hasPermission('order:item:export')")
    @OperateLog(type = EXPORT)
    public void exportItemExcel(@Valid OrderItemExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<OrderItemDO> list = itemService.getItemList(exportReqVO);
        // 导出 Excel
        List<OrderItemExcelVO> datas = OrderItemConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "订单项.xls", "数据", OrderItemExcelVO.class, datas);
    }

}
